#region (c) 2014 THN Solutions LLC. - All rights reserved
/*
Simplified BSD License (BSD)
Copyright (c) 2014, THN Solutions LLC. ( www.ThnSolutions.com )
Author: Nguyễn, M. Hải                 ( www.Minh-Hai.com     )
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this 
      list of conditions and the following disclaimer.

    * Redistributions in binary form must reproduce the above copyright notice, 
      this list of conditions and the following disclaimer in the documentation 
      and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
*/
#endregion

#region Record of Change
//             							CHANGE HISTORY
// -------------------------------------------------------------------------------------
// |   DATE    | DEVELOPER  | DESCRIPTION                                              |
// -------------------------------------------------------------------------------------
// | 04-Nov-09 | HaiNM      | First creation.                                          |
// -------------------------------------------------------------------------------------
//
#endregion

#region Record of Audit
//             							REVIEW HISTORY
// -------------------------------------------------------------------------------------
// |   DATE    | REVIEWER   | NOTES                                                    |
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
//
#endregion

#region Using directives
using System;
using System.Drawing;
using System.Windows.Forms;
using System.ComponentModel;

using Thn;
using Thn.Interface.Utils;
#endregion

namespace Thn.Interface.Vcl
{
    /// <summary>
    /// A generic calendar control for selecting a date.
    /// </summary>
    [ToolboxItem(true), DefaultProperty("Date"), DefaultEvent("DateChanged"), ToolboxBitmap(typeof(ResourceBeacon), "Thn.Interface.Vcl.Resources.Icons.Calendar.bmp")]
#if DEBUG
    public
#else
    public
#endif
 class Calendar : ControlBase
    {
        #region Fields

        protected enum HitArea { Other, MonthUp, MonthDown, YearUp, YearDown, Calendar, Today };
        /// <summary>
        /// Area of hit-test.
        /// </summary>
        protected HitArea mCurrentHit = HitArea.Other;

        #endregion

        #region Properties

        #region Date
        private DateTime mDate;
        /// <summary>
        /// Gets/Sets the selected date.
        /// </summary>
        [Browsable(true), Category("Value"), Description("Selected date")]
        public DateTime Date
        {
            get { return mDate; }
            set
            {
                DateTime mPrevious = mDate;
                mDate = value;
                mRenderContext.DisplayDate = value;
                CalculateDates();
                Invalidate();
                OnDateChanged(mPrevious, mDate);
                RaiseDateChanged(mPrevious, mDate);
                RaiseValueChanged(EventArgs.Empty);
            }
        }
        #endregion

        #region Render Context
        private CalendarRenderContext mRenderContext = new CalendarRenderContext();
        /// <summary>
        /// Gets reference to current renderation context.
        /// </summary>
        protected CalendarRenderContext RenderContext
        {
            get { return mRenderContext; }
        }
        #endregion

        #endregion

        #region Events

        #region Date Changed
        /// <summary>
        /// This event is raised after property Date is changed.
        /// </summary>
        public event DateTimeValueChangedHandler DateChanged;

        /// <summary>
        /// Invoke event DateChanged
        /// </summary>
        protected void RaiseDateChanged(DateTime oldValue, DateTime newValue)
        {
            DateTimeValueChangedHandler handler = DateChanged;
            if (handler != null) handler(this, oldValue, newValue);
        }
        #endregion

        #region Value Changed
        /// <summary>
        /// This event is raised after property Date is changed.
        /// </summary>
        public event EventHandler ValueChanged;

        /// <summary>
        /// Invoke event ValueChanged
        /// </summary>
        protected void RaiseValueChanged(EventArgs args)
        {
            EventHandler handler = ValueChanged;
            if (handler != null) handler(this, args);
        }
        #endregion

        #endregion

        #region Set Date
        /// <summary>
        /// Set value for property Date without causing event DateChanged to be fired.
        /// </summary>
        public void SetDate(DateTime value)
        {
            DateTime previous = mDate;
            mDate = value;
            mRenderContext.DisplayDate = value;
            CalculateDates();
            OnDateChanged(previous, mDate);
            Invalidate();
        }
        #endregion

        #region On Date Changed
        /// <summary>
        /// This method is invoked when property Date is modified.
        /// </summary>
        protected virtual void OnDateChanged(DateTime oldValue, DateTime newValue) { }
        #endregion

        #region On Get Render Context
        /// <summary>
        /// Get reference to the renderation context which is used by <see cref="IControlRenderer"/>.
        /// </summary>
        protected override RenderContext OnGetRenderContext(Graphics canvas)
        {
            return mRenderContext;
        }
        #endregion

        #region On Calculate Layout
        /// <summary>
        /// Perform layout calculations neccessary for this control.
        /// </summary>
        protected override void OnCalculateLayout()
        {
            Rectangle r = ClientRectangle;
            Rectangle rHeader = new Rectangle(r.Left, r.Top, r.Width - 1, r.Height / 6);
            Rectangle rDays = new Rectangle(rHeader.Left, rHeader.Bottom + 1, rHeader.Width, (r.Height - rHeader.Height) / 8);
            Rectangle rToday = new Rectangle(rHeader.Left, r.Bottom - r.Height / 7, rHeader.Width, r.Height / 7);
            Rectangle rCalendar = new Rectangle(rHeader.Left + 2, rDays.Bottom + 2, rHeader.Width, r.Height - rHeader.Height - rDays.Height - rToday.Height);
            Rectangle rBody = new Rectangle(r.Left, rCalendar.Top, rHeader.Width, rToday.Bottom - rCalendar.Top);

            //assign values to render context
            mRenderContext.HeaderRegion = rHeader;
            mRenderContext.TodayRegion = rToday;
            mRenderContext.DaysRegion = rDays;
            mRenderContext.CalendarRegion = rCalendar;
            mRenderContext.BodyRegion = rBody;

            //calculate dates grid
            int dx = rCalendar.Width / 7;
            int dy = rCalendar.Height / 6;
            int[] cols = mRenderContext.Columns;
            int[] rows = mRenderContext.Rows;

            cols[0] = rCalendar.Left; rows[0] = rCalendar.Top;

            int i = 0;
            for (i = 1; i < 7; i++)
            {
                cols[i] = cols[i - 1] + dx;
                rows[i] = rows[i - 1] + dy;
            }
            cols[7] = cols[6] + dx;

            //buttons
            int y = rHeader.Top + rHeader.Height / 4;
            int x = rHeader.Left + 5;
            dy = rHeader.Height - (rHeader.Height / 4) * 2;
            dx = rHeader.Height / 2;
            Rectangle rMonthUp = new Rectangle(x, y, dx, dy);
            Rectangle rMonthDown = new Rectangle(rMonthUp.Right + 1, y, dx, dy);
            Rectangle rYearDown = new Rectangle(rHeader.Right - 5 - dx, y, dx, dy);
            Rectangle rYearUp = new Rectangle(rYearDown.Left - 1 - dx, y, dx, dy);
            mRenderContext.PreviousMonthRegion = rMonthDown;
            mRenderContext.NextMonthRegion = rMonthUp;
            mRenderContext.PreviousYearRegion = rYearDown;
            mRenderContext.NextYearRegion = rYearUp;

            //title
            mRenderContext.TitleRegion = new Rectangle(rMonthDown.Right + 5, rMonthDown.Top, rYearUp.Left - rMonthDown.Right - 10, rMonthDown.Height);
        }
        #endregion

        #region Calculate Dates
        void CalculateDates()
        {
            DateTime date = mRenderContext.DisplayDate;
            DateTime firstDate = DateTimeHelper.FirstDateOfMonth(date);
            DateTime lastDate = DateTimeHelper.LastDateOfMonth(date);
            DateTime lastMonth = date;
            DateTime today = DateTime.Now;
            DateTime selected = mDate;
            int todayMonth = today.Month;
            int todayDay = today.Day;
            int todayYear = today.Year;
            int selectedMonth = selected.Month;
            int selectedDay = selected.Day;
            int selectedYear = selected.Year;
            int displayMonth = date.Month;
            int displayYear = date.Year;
            int startColumn = 0;
            int startRow = 0;
            int endColumn = 0;
            int endRow = 0;
            int i = 0;
            int[] Cols = mRenderContext.Columns;
            int[] Rows = mRenderContext.Rows;
            int[][] dates = mRenderContext.Dates;

            #region Reset render context
            mRenderContext.TodayIndex = -1;
            mRenderContext.SelectedIndex = -1;
            #endregion

            #region Calculate previous month
            try
            {
                if (lastMonth.Month > 1) lastMonth = new DateTime(lastMonth.Year - 1, 12, lastMonth.Day);
                else lastMonth = lastMonth.AddMonths(-1);
            }
            catch { }
            #endregion

            #region Find the days locations
            switch (firstDate.DayOfWeek)
            {
                case DayOfWeek.Sunday:
                    startColumn = 0;
                    startRow = 1;
                    break;
                case DayOfWeek.Monday:
                    startColumn = 1;
                    startRow = 0;
                    break;
                case DayOfWeek.Tuesday:
                    startColumn = 2;
                    startRow = 0;
                    break;
                case DayOfWeek.Wednesday:
                    startColumn = 3;
                    startRow = 0;
                    break;
                case DayOfWeek.Thursday:
                    startColumn = 4;
                    startRow = 0;
                    break;
                case DayOfWeek.Friday:
                    startColumn = 5;
                    startRow = 0;
                    break;
                case DayOfWeek.Saturday:
                    startColumn = 6;
                    startRow = 0;
                    break;
            }
            #endregion

            #region Populate this month's dates

            //draw this month's dates
            int x = startColumn;
            int y = startRow;
            int daysInMonth = DateTime.DaysInMonth(date.Year, date.Month);
            for (i = 1; i <= daysInMonth; i++)
            {
                if (x >= 7) { x = 0; y++; }
                dates[y][x] = i;

                //mark today
                if ((displayYear == todayYear) && (displayMonth == todayMonth) && (i == todayDay))
                {
                    mRenderContext.TodayIndex = y * 7 + x;
                }
                #region Defensive tracing
                else
                {
                    //proceed normally
                }
                #endregion

                //mark selected
                if ((displayYear == selectedYear) && (displayMonth == selectedMonth) && (i == selectedDay))
                {
                    mRenderContext.SelectedIndex = y * 7 + x;
                }
                #region Defensive tracing
                else
                {
                    //proceed normally
                }
                #endregion

                //next iteration
                x++;
            }
            endColumn = x;
            endRow = y;
            if (endColumn >= 7) { endColumn = 0; endRow++; }

            #endregion

            #region Populate next month's dates
            i = 1;
            while (true)
            {
                if ((y == 5) && (x == 7)) break;
                if (x >= 7) { x = 0; y++; }
                dates[y][x] = i;

                //next iteration
                x++;
                i++;
            }
            #endregion

            #region Populate previous month's dates
            if ((startColumn > 0) || (startRow > 0))
            {
                x = DateTime.DaysInMonth(lastMonth.Year, lastMonth.Month);
                if (startRow == 1) i = 6;
                else i = startColumn - 1;
                while (i >= 0)
                {
                    dates[0][i] = x;

                    //next iteration
                    x--;
                    i--;
                }
            }
            #endregion

            #region Save to context
            mRenderContext.StartColumn = startColumn;
            mRenderContext.StartRow = startRow;
            mRenderContext.EndColumn = endColumn;
            mRenderContext.EndRow = endRow;

            #endregion
        }

        #endregion

        #region On Click
        protected override void OnClick(EventArgs e)
        {
            //set focus to this control if not focused yet
            if (!Focused) Focus();
            #region Defensive tracing
            else
            {
                //already focused
            }
            #endregion
        }
        #endregion

        #region Navigation

        #region Next Month
        /// <summary>
        /// Go to next month.
        /// </summary>
        public void NextMonth()
        {
            mRenderContext.DisplayDate = mRenderContext.DisplayDate.AddMonths(1);
            CalculateDates();
            Invalidate();
        }
        #endregion

        #region Last Month
        /// <summary>
        /// Go to last month
        /// </summary>
        public void LastMonth()
        {
            mRenderContext.DisplayDate = mRenderContext.DisplayDate.AddMonths(-1);
            CalculateDates();
            Invalidate();
        }
        #endregion

        #region Next Year
        /// <summary>
        /// Go to Next year
        /// </summary>
        public void NextYear()
        {
            mRenderContext.DisplayDate = mRenderContext.DisplayDate.AddYears(1);
            CalculateDates();
            Invalidate();
        }
        #endregion

        #region Last Year
        /// <summary>
        /// Go to last year
        /// </summary>
        public void LastYear()
        {
            mRenderContext.DisplayDate = mRenderContext.DisplayDate.AddYears(-1);
            CalculateDates();
            Invalidate();
        }
        #endregion

        #endregion

        #region Hit-testing

        private HitArea GetHitArea(int x, int y)
        {
            CalendarRenderContext rc = mRenderContext;
            if (rc.CalendarRegion.Contains(x, y)) return HitArea.Calendar;
            else if (rc.PreviousMonthRegion.Contains(x, y)) return HitArea.MonthUp;
            else if (rc.NextMonthRegion.Contains(x, y)) return HitArea.MonthDown;
            else if (rc.PreviousYearRegion.Contains(x, y)) return HitArea.YearUp;
            else if (rc.NextYearRegion.Contains(x, y)) return HitArea.YearDown;
            else if (rc.TodayRegion.Contains(x, y)) return HitArea.Today;
            return HitArea.Other;
        }

        private int GetCol(int x)
        {
            int[] cols = mRenderContext.Columns;
            for (int i = 1; i <= 7; i++)
            {
                if (x <= cols[i]) return i - 1;
            }
            return -1;
        }

        private int GetRow(int y)
        {
            int[] rows = mRenderContext.Rows;
            for (int i = 1; i <= 6; i++)
            {
                if (y <= rows[i]) return i - 1;
            }
            return -1;
        }

        #endregion

        #region Keyboard Events

        #region Process Cmd Key
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            bool r = false;
            switch (keyData)
            {
                case Keys.Left:
                    LastMonth();
                    r = true;
                    break;
                case Keys.Right:
                    NextMonth();
                    r = true;
                    break;
                case Keys.Up:
                    LastYear();
                    r = true;
                    break;
                case Keys.Down:
                    NextYear();
                    r = true;
                    break;
            }
            if (r) return r;
            else return base.ProcessCmdKey(ref msg, keyData);
        }
        #endregion

        #endregion

        #region Mouse Events

        #region On Mouse Enter
        protected override void OnMouseEnter(EventArgs e)
        {
            if (Enabled)
            {
                mRenderContext.IsMouseOver = true;
                Invalidate();
            }
            #region Defensive tracing
            else
            {
                //currently disabled, no need to handle anything
            }
            #endregion
        }
        #endregion

        #region On Mouse Leave
        protected override void OnMouseLeave(EventArgs e)
        {
            if (Enabled)
            {
                mRenderContext.IsMouseOver = false;
                Invalidate();
            }
            #region Defensive tracing
            else
            {
                //currently disabled, no need to handle anything
            }
            #endregion
        }
        #endregion

        #region On Mouse Down
        protected override void OnMouseDown(MouseEventArgs e)
        {
            if (Enabled)
            {
                switch (mCurrentHit)
                {
                    case HitArea.MonthDown:
                        LastMonth();
                        break;
                    case HitArea.MonthUp:
                        NextMonth();
                        break;
                    case HitArea.YearDown:
                        LastYear();
                        break;
                    case HitArea.YearUp:
                        NextYear();
                        break;
                    case HitArea.Today:
                        Date = DateTime.Today;
                        break;
                    case HitArea.Calendar:
                        //finding the row and column 
                        int col = GetCol(e.X);
                        int row = GetRow(e.Y);
                        int startColumn = mRenderContext.StartColumn;
                        int startRow = mRenderContext.StartRow;
                        int endColumn = mRenderContext.EndColumn;
                        int endRow = mRenderContext.EndRow;

                        if ((col >= 0) && (row >= 0))
                        {
                            if ((row == 0) && ((col < startColumn) || (startRow > 0))) // previous month
                            {
                                LastMonth();
                            }
                            else if ((row > endRow) || ((row == endRow) && (col >= endColumn)))//next month
                            {
                                NextMonth();
                            }
                            else //this month
                            {
                                int counter = 1;
                                int c = startColumn; int r = startRow;
                                while ((r != row) || (c != col))
                                {
                                    counter++;
                                    c++;
                                    if (c == 7) { c = 0; r++; }
                                }
                                DateTime displayDate = mRenderContext.DisplayDate;
                                Date = new DateTime(displayDate.Year, displayDate.Month, counter);
                            }
                        }
                        break;
                }
            }
            #region Defensive tracing
            else
            {
                //currently disabled, no need to handle anything
            }
            #endregion
        }
        #endregion

        #region On Mouse Up
        //protected override void OnMouseUp(MouseEventArgs e)
        //{
        //    if (Enabled)
        //    {
        //        if (mRenderContext.State == CalendarState.Pressed)
        //        {
        //            mRenderContext.State = CalendarState.Over;
        //            Invalidate();
        //        }
        //        #region Defensive tracing
        //        else
        //        {
        //            //not interested in other state
        //        }
        //        #endregion
        //    }
        //    #region Defensive tracing
        //    else
        //    {
        //        //currently disabled, no need to handle anything
        //    }
        //    #endregion
        //}
        #endregion

        #region On Mouse Move
        protected override void OnMouseMove(MouseEventArgs e)
        {
            HitArea a = GetHitArea(e.X, e.Y);
            if (a != mCurrentHit)
            {
                mCurrentHit = a;
                Invalidate();
            }
            base.OnMouseMove(e);
        }
        #endregion

        #endregion

        #region On Lost Focus
        protected override void OnLostFocus(EventArgs e)
        {
            mRenderContext.IsMouseOver = false;
            base.OnLostFocus(e);
            Invalidate();
        }
        #endregion

        #region Constructors
        /// <summary>
        /// Default constructor.
        /// </summary>
        public Calendar()
        {
            mRenderContext = new CalendarRenderContext();
            mDate = DateTime.Now;
            mRenderContext.DisplayDate = mDate;
            CalculateDates();
            this.Size = new Size(187, 150);
        }
        #endregion
    }
}
